﻿using UnityEngine;
using UnityEngine.UI;
using Jinndev.UI;

namespace Jinndev {

    public class TileAnchorUI : BaseUIBehaviour {

        #region static
        public static readonly string PATH = "Prefab/UI/MapEditor/Tile/TileAnchorUI";

        /// <summary>
        /// 编辑锚点
        /// </summary>
        /// <param name="onConfirm">确定回调</param>
        public static TileAnchorUI Create(Vector2 curAnchor, System.Action<Vector2> onConfirm) {
            var com = UIManager.Instance.Add<TileAnchorUI>(PATH, UIParam.ModalPanel);
            com.Init(curAnchor, onConfirm);
            return com;
        }
        #endregion


        public InputField inputX;
        public InputField inputY;
        public Text textError;

        private Vector2 curAnchor;
        private System.Action<Vector2> onConfirm;

        private void Awake() {
            textError.text = string.Empty;
        }

        private void Start() {
            inputY.Select();
        }

        private void Update() {
            if (Input.GetKeyDown(KeyCode.Tab)) {
                if (inputX.isFocused) {
                    inputY.Select();
                }
                else {
                    inputX.Select();
                }
            }
            else if (Input.GetKeyDown(KeyCode.KeypadEnter)) {
                OnClickConfirm();
            }
        }

        private void Init(Vector2 curAnchor, System.Action<Vector2> onConfirm) {
            this.curAnchor = curAnchor;
            this.onConfirm = onConfirm;

            inputX.text = curAnchor.x + "";
            inputY.text = curAnchor.y + "";
        }

        public void OnClickConfirm() {
            Destroy(gameObject);
            Vector2 anchor = new Vector2();
            float.TryParse(inputX.text, out anchor.x);
            float.TryParse(inputY.text, out anchor.y);
            onConfirm?.Invoke(anchor);
        }

    }

}
